package lambdasinaction.chap11.CountDownLatch;

import java.util.concurrent.CountDownLatch;

/**
 * 确保多个线程在同一时刻开始执行。主线程等待所有工作线程就绪后，使用 CountDownLatch 释放它们以同时开始工作。
 */
public class StartThreadsSimultaneously {

    public static void main(String[] args) throws InterruptedException {
        int numberOfThreads = 3;
        CountDownLatch startSignal = new CountDownLatch(1);
        CountDownLatch doneSignal = new CountDownLatch(numberOfThreads);

        for (int i = 0; i < numberOfThreads; i++) {
            new Thread(new SimultaneousThread(startSignal, doneSignal)).start();
        }

        System.out.println("Releasing start signal...");
        startSignal.countDown(); // All worker threads start simultaneously
        doneSignal.await(); // Wait for all worker threads to finish
        System.out.println("All workers have finished. Main thread proceeds.");
    }
}

class SimultaneousThread implements Runnable {
    private final CountDownLatch startSignal;
    private final CountDownLatch doneSignal;

    public SimultaneousThread(CountDownLatch startSignal, CountDownLatch doneSignal) {
        this.startSignal = startSignal;
        this.doneSignal = doneSignal;
    }

    @Override
    public void run() {
        try {
            startSignal.await(); // Wait for the start signal
            System.out.println("Worker " + Thread.currentThread().getId() + " is working...");
            Thread.sleep(2000); // Simulate work
            System.out.println("Worker " + Thread.currentThread().getId() + " has finished.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            doneSignal.countDown(); // Decrement the count of the done signal
        }
    }
}
